import Vue from 'vue';
import VueRouter from 'vue-router';
import {routers} from './router';
import Cookies from 'js-cookie';
import {getMenuList} from '@/api/api';

Vue.use(VueRouter);

// 路由配置
const RouterConfig = {
    mode:'history',
    routes: routers
};

export const router = new VueRouter(RouterConfig);

router.beforeEach((to, from, next) => {
    // 判断是否已经登录且前往的页面不是登录页
    if (!Cookies.get('userInfo') && to.path != '/login') {
        next({
            path: '/login'
        });
    } else if (to.path !='/login' && to.path !='/main') { //主页和登录页不进行拦截
        //进行权限的校验
        let flag = false;
        getMenuList().then(data=>{
            let menuData = data.data;
            if (data.code == 200){
                //判断子节点是否有当前访问的路径
                for (var item of menuData) {
                    if (item.children && item.children.length > 0) {
                        for (var c of item.children) {
                            if (c.path == to.path){
                                flag = true;
                            }
                        }
                    }
                }
                if (flag){
                    next();
                }else {
                    next({
                        path: '/login'
                    });
                }
            }else {
                next({
                    path: '/login'
                })
            }
        })
    }else {
        next()
    }
});

router.afterEach((to) => {

});
